package com.by.file.controller;


import com.by.common.core.bean.ResultBean;

import com.by.common.core.controller.BaseController;
import com.by.file.config.MinioConfig;
import com.by.file.config.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("api/")
public class MinioController extends BaseController {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig prop;

    @Autowired
    HttpServletResponse res;



    //列出所有桶名称
    @GetMapping("/getAllBuckets")
    public ResultBean  getAllBuckets() {
        List<String> list = minioUtil.getAllBuckets();
        return success("所有桶的名称", list);
    }

    //查看存储bucket是否存在
    @GetMapping("/bucketExists")
    public ResultBean bucketExists(@RequestParam("bucketName") String bucketName) {
        return minioUtil.bucketExists(bucketName)==true?success("存在"):fail("不存在");
    }

    //创建存储bucket
    @GetMapping("/makeBucket")
    public ResultBean makeBucket(@RequestParam("bucketName") String bucketName) {
        return minioUtil.makeBucket(bucketName)==true?success("创建成功"):fail("创建失败");
    }

    //删除存储bucket
    @GetMapping("/removeBucket")
    public ResultBean removeBucket(@RequestParam("bucketName") String bucketName) {
        return minioUtil.removeBucket(bucketName)==true?success("删除成功"):fail("删除失败");
    }

    //文件上传返回url
    @PostMapping("/upload")
    public ResultBean upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        String path;
        if (null != objectName) {
            path = prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName;
            return success("上传成功", path);
        }
        return fail("上传失败");
    }

    //图片/视频预览
    @GetMapping("/preview")
    public ResultBean preview(@RequestParam("fileName") String fileName) {
        return success(minioUtil.preview(fileName));
    }

    //文件下载
    @GetMapping("/download")
    public ResultBean download(@RequestParam("fileName") String fileName) {
        minioUtil.download(fileName,res);
        return success("下载成功");
    }

    //删除文件 根据url地址删除文件
    @PostMapping("/delete")
    public ResultBean remove(@RequestParam("url") String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName()+"/") + prop.getBucketName().length()+1);
        return minioUtil.remove(objName)==true?success("删除成功"):fail("删除失败");
    }
}
